package cn.xetsoft.supermarket.view.Goods;

import cn.xetsoft.supermarket.common.DataResponse;
import cn.xetsoft.supermarket.dao.impl.GoodDaoImpl;
import cn.xetsoft.supermarket.entity.Good;
import cn.xetsoft.supermarket.service.GoodService;
import cn.xetsoft.supermarket.service.impl.GoodServiceImpl;
import cn.xetsoft.supermarket.util.GUITools;
import cn.xetsoft.supermarket.util.PropertiesUtil;
import cn.xetsoft.supermarket.view.ExportDataFrame;
import cn.xetsoft.supermarket.view.FuncionFrame;
import cn.xetsoft.supermarket.util.ViewDataUtil;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

/**
 * 商品管理页面
 */
@SuppressWarnings("serial")
public  class GoodsFrame extends JFrame{

    GoodService goodService = new GoodServiceImpl(new GoodDaoImpl());
    //定义界面使用到的组件作为成员变量
    protected JTextField searchText = new JTextField(6);//搜索框
    private JButton searchBtn = new JButton("搜索");//搜索按钮
    private JScrollPane GoodsPane = new JScrollPane();//滚动视口
    protected JTable table = new JTable(){
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }; //水果列表

    //添加功能组件
    private JButton addBtn = new JButton("添加商品");//添加按钮
    //修改功能组件
    private JButton updateBtn = new JButton("修改商品");//修改按钮
    //删除功能组件
    private JButton delBtn = new JButton("删除商品");//删除按钮
    //导出EXCEL
    private JButton exportBtn = new JButton("导出EXCEL");
    //返回功能组件
    private JButton reBtn = new JButton("返回");//删除按钮

    //背景图
    private JLayeredPane layeredPane;
    private ImageIcon image;
    private JPanel jp;
    private JLabel jl;
    int xOld = 0;
    int yOld = 0;

    //构造方法
    public GoodsFrame() {
        this.init();// 初始化操作
        this.addComponent();// 添加组件
        this.addListener(this);// 添加监听器
        LodingGood(this.table);
    }
    // 初始化操作
    private void init() {
        this.setTitle("商品管理 - 熵客云超市欢迎您!");// 标题
        this.setSize(1286, 642);// 窗体大小与位置
        GUITools.center(this);//设置窗口在屏幕上的位置
        this.setResizable(false);// 窗体大小固定

        //按住窗体可以拖动
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xOld = e.getX();
                yOld = e.getY();
            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int xOnScreen = e.getXOnScreen();
                int yOnScreen = e.getYOnScreen();

                int xx = xOnScreen - xOld;
                int yy = yOnScreen - yOld;
                GoodsFrame.this.setLocation(xx, yy);
            }
        });
    }
    // 添加组件
    private void addComponent() {

        layeredPane=new JLayeredPane();
        /**
         * 得到路径区别开发环境和jar包
         */
        String imgFile = "Images/GoodBgImg.png";
        if (!PropertiesUtil.getProperty("debug.resources.type").equals("jar")){
            imgFile = Class.class.getResource("/").getPath() + imgFile;
        }
        image=new ImageIcon(imgFile);//背景图片
        //创建背景
        jp=new JPanel();
        jp.setBounds(0,-10,image.getIconWidth(),642);

        jl=new JLabel(image);
        jl.setBounds(0,0,image.getIconWidth(),642);
        jp.add(jl);
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// 设置table内容居中
        //搜索框
        searchText.setBounds(32,120,365,50);
        searchText.setText("商品搜索框");
        //搜索按钮
        searchText.setForeground(Color.GRAY);
        searchBtn.setBounds(400,120,160,50);
        //添加按钮
        addBtn.setBounds(569, 120,130, 50);
        //修改组件
        updateBtn.setBounds(706, 120,130, 50);
        //删除组件
        delBtn.setBounds(845, 120, 130, 50);
        //导出EXCEL
        exportBtn.setBounds(983, 120, 130, 50);
        //返回组件
        reBtn.setBounds(1122, 120, 130, 50);
        //商品表格
        table.getTableHeader().setReorderingAllowed(false);	//列不能移动
        table.getTableHeader().setResizingAllowed(false); 	//不可拉动表格
        table.setDefaultRenderer(Object.class,tcr);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.getTableHeader().setReorderingAllowed(false);

        GoodsPane.setBounds(27, 178, 1233, 435);
        GoodsPane.setViewportView(table);					//视口装入表格

        //将jp放到最底层。
        layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER);

        //将控件放到高一层的地方
        layeredPane.add(searchText,JLayeredPane.MODAL_LAYER);
        layeredPane.add(searchBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(addBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(updateBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(delBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(exportBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(reBtn,JLayeredPane.MODAL_LAYER);
        layeredPane.add(GoodsPane,JLayeredPane.MODAL_LAYER);

        this.setLayeredPane(layeredPane);
        this.setSize(image.getIconWidth(),667);
        this.setVisible(true);
        this.requestFocusInWindow();


    }
    // 添加监听器
    private void addListener(GoodsFrame goodsFrame) {
        //添加按钮监听
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //打开添加页面
                new GoodsAddFrame(goodsFrame).setVisible(true);
            }
        });
        //修改按钮监听
        updateBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //打开修改页面
                //打开修改页面前判断是否选中数据
                if (table.getSelectedColumnCount() == 0 || table.getSelectedRowCount() == 0){
                    JOptionPane.showMessageDialog(null,"请选中要修改的项目！");
                    return;
                }
                //调用修改方法
                DataResponse<Good> goodDataResponse = goodService.queryById(Integer.valueOf(table.getValueAt(table.getSelectedRow(), 0).toString()));//根据选中的商品ID进行查询,0是表第一个字段也就是Gid
                new GoodsModifyFrame(goodDataResponse.getData(),goodsFrame).setVisible(true);
//
            }
        });

        reBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                //返回按钮
                goodsFrame.setVisible(false);
            }
        });
        //商品搜索
        searchText.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                String temp = searchText.getText();
                if (!temp.equals("")){
                    searchText.setText("");
                    searchText.setForeground(Color.BLACK);
                }

            }

            @Override
            public void focusLost(FocusEvent e) {
                String temp = searchText.getText();
                if (temp.equals("")){
                    searchText.setForeground(Color.GRAY);
                    searchText.setText("商品搜索框");
                }
            }
        });
        //导出按钮
        exportBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new ExportDataFrame();
            }
        });
        //搜索按钮
        searchBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //根据搜索框输入的内容从数据库内匹配数据
                String search = searchText.getText();
                if (search.equalsIgnoreCase("商品搜索框") || search.trim().equalsIgnoreCase("")){
                   goodsFrame.LodingGood(goodsFrame.table);
                    return;
                }
                DataResponse<List<Good>> listDataResponse = goodService.queryByGoodnameAndGoodbrand(search);
                if (listDataResponse.isSuccess()){
                    ViewDataUtil viewDataUtil = new ViewDataUtil();
                    String[][] tbody = new String[0][];
                    tbody = viewDataUtil.GoodlistToArrays(listDataResponse.getData());
                    String[] thead = new String[]{"商品编号","商品名称","商品品牌","销售单价(/元)","进货单价(/元)","计价单位","库存","创建时间","上次维护时间"};
                    TableModel dataModel = new DefaultTableModel(tbody, thead);
                    table.setModel(dataModel);
                }else {
                    JOptionPane.showMessageDialog(null,"该分类查无内容，请更换关键词！");
                }

            }
        });
        //删除商品
        delBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //删除选择的数据
                //删除前判断是否选中
                if (table.getSelectedColumnCount() == 0 || table.getSelectedRowCount() == 0){
                    JOptionPane.showMessageDialog(null,"请选中要修改的项目！");
                    return;
                }
                int gid = Integer.valueOf( table.getValueAt(table.getSelectedRow(),0).toString());
                DataResponse dataResponse = goodService.deleteById(gid);
                if (dataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,"删除成功！");
                    goodsFrame.LodingGood(table);
                }else {
                    JOptionPane.showMessageDialog(null,"删除失败！");
                }
            }
        });

        //选中表格监听器
        table.addMouseListener(new MouseAdapter() {
            /**
             * {@inheritDoc}
             *
             * @param e
             */
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (table.getSelectedRowCount() == 0 || table.getSelectedColumnCount() == 0){
                    JOptionPane.showMessageDialog(null,"尚未选中任何商品");
                }
                String date = table.getValueAt(table.getSelectedRow(),8).toString();
                JOptionPane.showMessageDialog(null,"过期时间："+ date);
            }
        });

    }
    //在页面加载的时候对取出数据并且加载到页面上
    public void LodingGood(JTable table){
        ViewDataUtil viewDataUtil = new ViewDataUtil();
        String[][] tbody = new String[0][];
        DataResponse<List<Good>> listDataResponse = goodService.queryAll();
        if (listDataResponse.isSuccess()){//操作成功
            List<Good> goodList = listDataResponse.getData();
            System.out.println(goodList);
            tbody = viewDataUtil.GoodlistToArrays(goodList);
        } else {
            //不成功打印错误信息
            System.out.println(listDataResponse.getMsg());
        }
        String[] thead = new String[]{"商品编号","商品名称","商品品牌","销售单价(/元)","进货单价(/元)","计价单位","库存","创建时间","过期时间","上次维护时间"};//表头
        TableModel dataModel = new DefaultTableModel(tbody, thead);
        table.setModel(dataModel);
    }


}
